package com.tulingxueyuan.mall.controller;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tulingxueyuan.mall.common.api.CommonResult;
import com.tulingxueyuan.mall.common.api.ResultCode;
import com.tulingxueyuan.mall.common.exception.ApiException;
import com.tulingxueyuan.mall.dto.ConfimOrderDto;
import com.tulingxueyuan.mall.dto.OrderDetailDto;
import com.tulingxueyuan.mall.dto.OrderParamDto;
import com.tulingxueyuan.mall.modules.oms.mapper.OmsCartItemMapper;
import com.tulingxueyuan.mall.modules.oms.model.OmsCartItem;
import com.tulingxueyuan.mall.modules.oms.model.OmsOrder;
import com.tulingxueyuan.mall.modules.oms.model.OmsOrderItem;
import com.tulingxueyuan.mall.modules.oms.model.OmsOrderSetting;
import com.tulingxueyuan.mall.modules.oms.service.OmsCartItemService;
import com.tulingxueyuan.mall.modules.oms.service.OmsOrderItemService;
import com.tulingxueyuan.mall.modules.oms.service.OmsOrderService;
import com.tulingxueyuan.mall.modules.oms.service.OmsOrderSettingService;
import com.tulingxueyuan.mall.modules.pms.model.PmsProduct;
import com.tulingxueyuan.mall.modules.pms.model.PmsSkuStock;
import com.tulingxueyuan.mall.modules.pms.service.PmsProductService;
import com.tulingxueyuan.mall.modules.pms.service.PmsSkuStockService;
import com.tulingxueyuan.mall.modules.ums.model.UmsMember;
import com.tulingxueyuan.mall.modules.ums.model.UmsMemberReceiveAddress;
import com.tulingxueyuan.mall.modules.ums.service.UmsMemberReceiveAddressService;
import com.tulingxueyuan.mall.modules.ums.service.UmsMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

@RestController
@RequestMapping("/order")
@Api(tags = "order",description = "订单")
public class OrderController {
    @Autowired
    OmsCartItemService cartItemService;
    @Autowired
    UmsMemberService memberService;
    @Autowired
    PmsProductService productService;
    @Autowired
    UmsMemberReceiveAddressService receiveAddressService;
    @Autowired
    OmsOrderService orderService;
    @Autowired
    PmsSkuStockService skuStockService;
    @Autowired
    OmsOrderItemService orderItemService;
    @Autowired
    OmsOrderSettingService orderSettingService;
    /**
     * 根据选中的购物车商品  生成订单页面初始化
     */
    @PostMapping("/generateConfirmOrder")
    public CommonResult generateConfigOrder(@RequestBody Map map){
        List<String> itemIds = (List<String>) map.get("itemIds");
        if (CollectionUtils.isEmpty(itemIds)){
//            throw new ApiException(ResultCode.VALIDATE_FAILED);
//            说明是立即结算
            String skuId =  map.get("skuId").toString();
            PmsSkuStock skuStock = skuStockService.getById(skuId);
//            ConfimOrderDto confimOrderDto = new ConfimOrderDto();
//            BeanUtils.copyProperties(skuStock,confimOrderDto);
            PmsProduct product = productService.getById(skuStock.getProductId());
            List<Object> productAndSku = new ArrayList<>();
            productAndSku.add(product);
            productAndSku.add(skuStock);
            return CommonResult.success(productAndSku);
        }else {
//       1：勾选的购物车商品
            UmsMember umsMember = memberService.getCurrentMember();
            LambdaQueryWrapper<OmsCartItem> lqw = new LambdaQueryWrapper<>();
            lqw.in(OmsCartItem::getId, itemIds);
            lqw.eq(OmsCartItem::getMemberId, umsMember.getId());
            List<OmsCartItem> cartItemList = cartItemService.list(lqw);
            ConfimOrderDto confimOrderDto = new ConfimOrderDto();
            confimOrderDto.setCartItemList(cartItemList);
//        2：计算价格
            calcCatAmount(confimOrderDto);
//        3：收货地址
            LambdaQueryWrapper<UmsMemberReceiveAddress> lqw1 = new LambdaQueryWrapper<>();
            lqw1.eq(UmsMemberReceiveAddress::getMemberId, umsMember.getId());
            List<UmsMemberReceiveAddress> addresses = receiveAddressService.list(lqw1);
            confimOrderDto.setMemberReceiveAddressList(addresses);
            return CommonResult.success(confimOrderDto);
        }
    }

    public void calcCatAmount(ConfimOrderDto confimOrderDto){
//        计算商品数量
        Integer productTotal=0;
//        总价
        BigDecimal priceTotal=new BigDecimal(0);
//        运费
        BigDecimal freightAmount = new BigDecimal(0);
//        BigDecimal payAmount=new BigDecimal(0);
        for (OmsCartItem cartItem : confimOrderDto.getCartItemList()) {
//            计算商品数量
            productTotal += cartItem.getQuantity();
//         总价   BigDecimal类型不能喝integer类型直接计算  需要转化成BigDecimal对象 之后调用对应方法计算
            priceTotal = priceTotal.add(cartItem.getPrice().multiply(new BigDecimal(cartItem.getQuantity())));
            PmsProduct product = productService.getById(cartItem.getProductId());
            String serviceIds = product.getServiceIds();
//            拿到对应的1,2,3  3是是否包邮
            String[] strings = serviceIds.split(",");
            if (strings.length>0){
//                判断是否包邮
                if(!ArrayUtil.containsAny(strings,3)){
//                    不包邮的话累加10元
                    freightAmount = freightAmount.add(new BigDecimal(10).multiply(new BigDecimal(cartItem.getQuantity())));
                }
            }
        }
        confimOrderDto.setProductTotal(productTotal);
        confimOrderDto.setFreightAmount(freightAmount);
        confimOrderDto.setPriceTotal(priceTotal);
        confimOrderDto.setPayAmount(priceTotal.add(freightAmount));
    }

    /**
     * 生成订单（下单）
     * 1:判断库存（没有库存直接提示）
     * 2：保存订单主表oms_order信息  订单号
     * 3：保存订单详情表oms_order_item 购物车转移
     * 4：锁定库存   如果用户超过10分钟没有支付则恢复库存
     * 5：删除对应购物车
     */
    @PostMapping("/generateOrder")
    public CommonResult generateOrder(@RequestBody OrderParamDto orderParamDto){
        OmsOrder omsOrder = orderService.generateOrder(orderParamDto);
        return CommonResult.success(omsOrder.getId());
    }

    /**
     * 读取下单成功后的订单详情
     */
    @GetMapping("/orderDetail")
    public CommonResult generateOrder(@RequestParam(value = "orderId") Long id){
        OmsOrder order = orderService.getById(id);
        OrderDetailDto orderDetailDto = new OrderDetailDto();
        BeanUtils.copyProperties(order,orderDetailDto);
        LambdaQueryWrapper<OmsOrderItem> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OmsOrderItem::getOrderSn,orderDetailDto.getOrderSn());
        List<OmsOrderItem> orderItemList = orderItemService.list(lqw);
        orderDetailDto.setOrderItemList(orderItemList);
        OmsOrderSetting orderSetting = orderSettingService.getById(1);
        orderDetailDto.setNormalOrderOvertime(orderSetting.getNormalOrderOvertime());
        return CommonResult.success(orderDetailDto);
    }

}
